import 'package:flutter/material.dart';
import 'package:mine_sweeping/block_container.dart';
import 'package:mine_sweeping/game_setting.dart';
import 'package:mine_sweeping/play_time.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GameSetting gameSetting = GameSetting()..init();

  @override
  void initState() {
    super.initState();
  }

  _buildAppBar() => AppBar(
        title: const Text(
          "Mine-Sweeping",
          style: TextStyle(fontSize: 20),
        ),
      );

  _buildTool() => Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Wrap(
            alignment: WrapAlignment.center,
            runAlignment: WrapAlignment.center,
            children: [
              const Icon(
                Icons.flag,
                color: Colors.red,
              ),
              Text(
                "${gameSetting.numFlags}",
                textAlign: TextAlign.center,
              )
            ],
          ),
          Wrap(
            children: [
              Icon(Icons.timer_sharp),
              PlayTime(),
            ],
          )
        ],
      );

  _buildBoard() => GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: gameSetting.numColumns,
            crossAxisSpacing: 2,
            mainAxisSpacing: 2),
        itemCount: gameSetting.difficult * gameSetting.difficult,
        itemBuilder: (context, index) {
          int i = index ~/ gameSetting.numColumns;
          int j = index % gameSetting.numColumns;
          BlockType blockType;
          //格子被翻开
          if (gameSetting.revealed[i][j]) {
            //是地雷
            if (gameSetting.board[i][j] == -1) {
              blockType = BlockType.mine;
            } else {
              blockType = BlockType.figure;
            }
          } else {
            //被用户标记
            if (gameSetting.flagged[i][j]) {
              blockType = BlockType.label;
            } else {
              blockType = BlockType.unlabeled;
            }
          }

          return BlockContainer(
            blockType: blockType,
            value: gameSetting.revealed[i][j] && gameSetting.board[i][j] != 0
                ? gameSetting.board[i][j]
                : 0,
            onTap: () {
              gameSetting.reveal(i, j);
              setState(() {});
              if (gameSetting.checkWin()) {
                showSnack(win: true);
              }
              if (gameSetting.gameOver) {
                showSnack(win: false);
              }
            },
            onDoubleTap: () => toggleFlag(i, j),
          );
        },
      );

  _buildBody() => SizedBox(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height - 20,
        child: Column(
          children: [
            _buildTool(),
            Expanded(
              child: _buildBoard(),
            )
          ],
        ),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(),
      backgroundColor: const Color(0xff09484F),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          gameSetting.init();
          setState(() {});
        },
        child: const Icon(Icons.refresh),
      ),
    );
  }

  ///标记雷
  void toggleFlag(int i, int j) {
    if (!gameSetting.gameOver) {
      setState(() {
        gameSetting.flagged[i][j] = !gameSetting.flagged[i][j];
        if (gameSetting.flagged[i][j]) {
          gameSetting.numFlags--;
        } else {
          gameSetting.numFlags++;
        }
      });
    }
    if (gameSetting.checkWin()) {
      showSnack(win: true);
    }
  }

  void showSnack({required bool win}) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(
      win ? "You WIN!" : "YOU LOSE!",
      style: TextStyle(color: win ? Colors.teal : Colors.red),
    )));
  }
}
